<template>
  <DynamicForm :config="dyModalConfig" :questions="dyModalQuestions" ref="modalRef">
    <template #upload="{ data }">
      <a-dropdown placement="bottom">
        <span class="form-table-actions">附件上传 <DownOutlined /></span>
        <template #overlay>
          <a-menu>
            <a-menu-item @click.prevent="onUpload(data)">
              <span>上传</span>
            </a-menu-item>
            <a-menu-item @click.prevent="associatedUpload(data)">
              <span>个人文件关联上传</span>
            </a-menu-item>
          </a-menu>
        </template>
      </a-dropdown>
      <span class="fileName" @click.prevent="previewFile(data)">{{ data.attachment?.name }}</span>
    </template>
  </DynamicForm>
  <AssociatedUploadDiaLog v-model:visible="state.showUpload" v-if="state.showUpload" :data="state.showData" :source="true" @fileData="getArchivesData"></AssociatedUploadDiaLog>
</template>
<script lang="ts" setup>
import { DynamicForm } from '@/components/public-template';
import { INITSERVE, SELECTSERVE, DYNAMICLAYERUPLOAD, DYNAMICLAYERCLEAR } from '@/mixins/subject/subject-types';
import { computed, getCurrentInstance, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue';
import indexService, { entityPages, inNameQuestion, otherPages, outNameQuestion } from './modalForm.service';
import { filter } from 'rxjs/operators';
import AssociatedUploadDiaLog from '@/views/fileManage/addDocumentApp/component/associatedUploadDiaLog.vue';
import { fileGetPreviewFileUrl } from '@/config/api/personFile';
import { getPreviewFileUrl } from '@/config/api/resourceFileInfo';
import XEUtils from 'xe-utils';
import { CODE_RULE, generateCode } from '@/config/api/authorityManage';
import { regExp } from '@/utils/regExp';

const props = defineProps({
  data: {
    type: Object
  },
  showType: {
    type: String
  },
  // 是否强添加
  isForce: {
    type: Boolean
  }
});
console.log(props.data, 44);

const emits = defineEmits(['update:data']);
const state = reactive({
  count: 1,
  showUpload: false,
  showData: {}, // modalRef的数据
  fileId: null // 附件id
});
const uuid = Date.now().toString();
const dyModalConfig: any = {
  name: uuid,
  labelCol: 8,
  wrapperCol: 16,
  grid: 6,
  layout: 'vertical',
  cancelSave: true
};
const modalRef = ref(null);
const { proxy }: any = getCurrentInstance();
const dyModalQuestions: any = reactive(
  ['ADD', 'EDIT'].includes(props.showType) ? indexService.getQuestions({ source: props.data.source, type: props.data.type }) : indexService.getViewQuestions(props.data.attachment.fileSource)
);
// 初始数据
initData();
function initData() {
  dyModalQuestions.forEach((item) => {
    // 设置value值
    item.value = props.isForce ? props.data[item.key] : props.data[item.key] ?? item.value;
    // 设置name值
    if (item.state && item.key !== 'attachment') item.state.name = uuid;
    if (item.key === 'chargeUserId' && dyModalQuestions[11].value && !['EDIT'].includes(props.showType)) {
      const option = findObjectById(dyModalQuestions[11].options, dyModalQuestions[11].value, 'childOrg');
      setFormData({ chargeUserId: option?.leader });
    }
  });
}

onMounted(() => {
  watch(
    () => modalRef.value.getDataFrom(),
    () => {
      emits('update:data', modalRef.value.getDataFrom());
    },
    { immediate: true }
  );
  // 监听导入的数据更新
  watch(
    () => props.data.attachment,
    (newVal, oldVal) => {
      JSON.stringify(newVal) != JSON.stringify(oldVal) && setFormData({ attachment: props.data.attachment });
    }
  );
  // 接口请求完再进行赋值
  watch(
    () => dyModalQuestions[11].options,
    () => {
      initData();
    }
  );
});
const isValidateFields = computed(() => {
  return modalRef.value.isValidateFields;
});
const getDataFrom = computed(() => {
  return modalRef.value.getDataFrom;
});
// 监听form
const subscribeSub = proxy.$NotificationFormSub
  .getParams()
  .pipe(filter((res) => res !== 0))
  .subscribe((item: any) => {
    if (item.key === SELECTSERVE && item.value.name == dyModalConfig.name) {
      if (item.value.key == 'source' && item.value.value) {
        for (let i = 0; i < dyModalQuestions.length; i++) {
          // 文件来源为系统内，文件名称为下拉选择框，系统外则文本输入框
          if (dyModalQuestions[i].key == 'name') {
            dyModalQuestions[i] = XEUtils.clone(item.value.value == 1 ? inNameQuestion : outNameQuestion, true);
            dyModalQuestions[i].value = null;
            if (dyModalQuestions[i].state) dyModalQuestions[i].state.name = uuid;
          }
          if (dyModalQuestions[i].key == 'code') {
            dyModalQuestions[i].value = item.value.value == 1 ? null : getFileCode();
          }
        }
        // 更新校验
        modalRef.value.initVerify();
      } else if (item.value.key == 'name') {
        // 获取文件编码
        const file = item.value.data.find((obj) => obj.name == item.value.value) || {};
        setFormData({ code: file.code, secretLevel: file.securityLevel });
      } else if (item.value.key == 'type') {
        for (let i = 0; i < dyModalQuestions.length; i++) {
          if (dyModalQuestions[i].key == 'filePages') {
            // 载体类型为实体，文件页数为空不可编辑，其他时必填
            // dyModalQuestions[i] = XEUtils.clone(item.value.value == 4 ? entityPages : otherPages, true);
            // dyModalQuestions[i].value = null;
            if (item.value.value == 4) {
              dyModalQuestions[i].value = null;
              dyModalQuestions[i].disabled = true;
              dyModalQuestions[i].required = false;
              dyModalQuestions[i].reg = null;
            } else {
              dyModalQuestions[i].disabled = false;
              dyModalQuestions[i].required = true;
              dyModalQuestions[i].reg = regExp.positiveInteger;
            }
            proxy.$NotificationFormSub.pushParams({
              key: INITSERVE,
              value: {
                initKeys: 'filePages',
                configName: 'uuid'
              }
            });
          }
        }
        // 更新校验
        modalRef.value.initVerify();
      } else if (item.value.key == 'filesType') {
        const option = findObjectById(item.value.data, item.value.value) || {};
        setFormData({ filesTypeName: option.name });
      } else if (item.value.key == 'chargeUserId') {
        const option = item.value.data.find((obj) => obj.id == item.value.value) || {};
        setFormData({ chargeUserName: option.nickName });
      } else if (item.value.key == 'toDepartment') {
        const option = findObjectById(item.value.data, item.value.value) || {};
        setFormData({ toDepartmentName: option.name });
        const option2 = findObjectById(item.value.data, item.value.value, 'childOrg') || {};
        setFormData({ chargeUserId: option2.leader });
      }
    }
  });

// 手动上传文件
function onUpload(fileData) {
  console.log(fileData, 111);

  proxy.$NotificationPubSub.pushParams({
    key: DYNAMICLAYERUPLOAD,
    value: {
      state: {
        size: '4096',
        downloadRule: '支持扩展名：.rar .zip .doc .docx .pdf .jpg...',
        beforeWithMethodRequireData: true,
        beforeWithMethod: (data) => {
          fileData.attachment = {
            sourceId: data.id,
            fileId: data.id,
            name: data.name,
            size: data.size,
            fileSource: 1
          };
          state.fileId = data.id;
          proxy.$NotificationPubSub.pushParams({ key: DYNAMICLAYERCLEAR });
        }
      }
    }
  });
}

// 个人文件关联上传
function associatedUpload(fileData) {
  state.showData = fileData;
  state.showUpload = true;
}
function getArchivesData(val) {
  setFormData({ attachment: val.attachment });
  modalRef.value.getData();
  state.fileId = val.attachment.sourceId;
}
// 文件预览
function previewFile(data) {
  const params = {
    id: state.fileId,
    expires: 2,
    timeUnit: 'HOURS'
  };
  if (data.attachment.fileSource === 2) {
    // 个人文件预览
    fileGetPreviewFileUrl(params).then((result) => {
      if (result && result.success) {
        window.open(result.data);
      }
    });
  } else {
    // 本地上传文件预览
    getPreviewFileUrl(params).then((result) => {
      if (result && result.success) {
        window.open(result.data);
      }
    });
  }
}
// 设置form值
function setFormData(assign) {
  for (let i = 0; i < dyModalQuestions.length; i++) {
    if (Object.prototype.hasOwnProperty.call(assign, dyModalQuestions[i].key)) {
      dyModalQuestions[i].value = assign[dyModalQuestions[i].key];
    }
  }
}
// 根据value查找对应树选择项
function findObjectById(arr, id, children = 'children') {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].id == id) {
      return arr[i];
    } else if (arr[i][children] && arr[i][children].length > 0) {
      const result = findObjectById(arr[i][children], id, children);
      if (result) {
        return result;
      }
    }
  }
  return null;
}

// 获取文件编码
function getFileCode() {
  const code = ref(null);
  const params = { type: CODE_RULE.WJBM_DAGD };
  generateCode(params).then((res) => {
    if (res.success && res.data.length) {
      code.value = res.data[0];
    }
  });
  return code;
}

onBeforeUnmount(() => {
  subscribeSub && subscribeSub.unsubscribe();
  proxy.$NotificationFormSub.clearParams();
});

//组件对外公开方法
defineExpose({
  isValidateFields: isValidateFields, //验证
  getDataFrom: getDataFrom //获取数据
});
</script>

<style lang="less" scoped>
.fileName {
  margin-left: 20px;
  color: #02a7f0;
  cursor: pointer;
}
</style>
